package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.dto.SecurityAdvisorServiceEnterpriseDto
import cn.exrick.xboot.base.entity.EnterpriseUser
import cn.exrick.xboot.base.entity.SecurityAdvisor
import cn.exrick.xboot.base.entity.SecurityAdvisorServiceEnterprise
import cn.exrick.xboot.base.mapper.SecurityAdvisorServiceEnterpriseMapper
import cn.exrick.xboot.base.service.IEnterpriseUserService
import cn.exrick.xboot.base.service.IMessageService
import cn.exrick.xboot.base.service.ISecurityAdvisorService
import cn.exrick.xboot.base.service.ISecurityAdvisorServiceEnterpriseService
import cn.exrick.xboot.base.vo.*
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*

/**
 * 安全顾问服务过的企业接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class ISecurityAdvisorServiceEnterpriseServiceImpl : ServiceImpl<SecurityAdvisorServiceEnterpriseMapper?, SecurityAdvisorServiceEnterprise?>(), ISecurityAdvisorServiceEnterpriseService {

    @Autowired
    private var iMessageService: IMessageService? = null

    @Autowired
    private var securityUtil: SecurityUtil? = null

    @Autowired
    private var iEnterpriseUserService: IEnterpriseUserService? = null

    @Autowired
    private val iSecurityAdvisorService: ISecurityAdvisorService? = null

    override fun getSecurityAdvisorServiceEnterpriseVoList(userId: String): MutableList<SecurityAdvisorServiceEnterpriseVo>? {

       return ToolUtil.setListToNul(list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::createBy, userId)
                .orderByDesc(SecurityAdvisorServiceEnterprise::createTime)))?.run {

            map {
                SecurityAdvisorServiceEnterpriseVo().apply {
                    enterpriseUserName = iEnterpriseUserService!!.getById(it!!.enterpriseUserId)?.companyName
                    ToolUtil.copyProperties(it, this) }
            }.toMutableList()
        }
    }

    override fun getServiceEnterpriseUser(pageVo: PageVo): Result<Map<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::createBy, securityUtil!!.currUser.id)
                .eq(SecurityAdvisorServiceEnterprise::serviceStatus, true).orderByDesc(SecurityAdvisorServiceEnterprise::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap();
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, map { iEnterpriseUserService!!.getEnterpriseUserVo(it!!.enterpriseUserId!!) }.toMutableList())

            return ResultUtil.data(result,"获取成功！")
        } ?: ResultUtil.error(201,"暂无数据")
    }

    override fun getServiceEnterpriseUserDetail(id: String): Result<EnterpriseUserDetailVo?>? {

        return iEnterpriseUserService!!.getEnterpriseDetail(id)
    }

    override fun getEnterpriseSecurityAdvisor(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java)
                .eq(SecurityAdvisorServiceEnterprise::enterpriseUserId, iEnterpriseUserService!!.getOne(KtQueryWrapper(EnterpriseUser::class.java)
                        .eq(EnterpriseUser::createBy, securityUtil!!.currUser.id))?.id)
                .eq(SecurityAdvisorServiceEnterprise::serviceStatus, true)
                .orderByDesc(SecurityAdvisorServiceEnterprise::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { iSecurityAdvisorService!!.getSecurityAdvisorVo(iSecurityAdvisorService
                    .getOne(KtQueryWrapper(SecurityAdvisor::class.java)
                    .eq(SecurityAdvisor::userId, it!!.createBy))?.id) }.toMutableList())

            ResultUtil.data(result, "获取数据成功！")
        } ?: ResultUtil.error(201, "暂无数据")
    }

    override fun getCompanySecurityAdvisorList(): Result<MutableList<EnterpriseSecurityAdvisorListVo>> {

        return ToolUtil.setListToNul(list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::enterpriseUserId,
                iEnterpriseUserService!!.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id)).eq(SecurityAdvisorServiceEnterprise::serviceStatus, true)))
                ?.run {

                    ResultUtil.data(mapNotNull { iSecurityAdvisorService!!.getSecurityEnterpriseAdvisorListVO(it!!.createBy) }.toMutableList(), "获取安全顾问列表成功")
                } ?: ResultUtil.error(201, "暂无数据！")
    }



    override fun removeEnterpriseSecurityAdvisor(ids: Array<out String>): Result<Any>? {

        return try {

            ids.forEach {

                getById(it)?.run {

                    serviceEndTime = Date()
                    serviceStatus = false
                    updateById(this)
                }
            }
            ResultUtil.success<Any>("操作成功!")
        } catch (e: Exception) {

            ResultUtil.error<Any>(e.message)
        }
    }

    override fun createSecurityAdvisorServiceEnterprise(securityAdvisorServiceEnterpriseDto: SecurityAdvisorServiceEnterpriseDto): Result<Any> {

        return iMessageService!!.getById(securityAdvisorServiceEnterpriseDto.messageId!!)?.run {

            //1消息设置为已读
            isRead = true
            iMessageService!!.updateById(this)

            //2.处理邀请消息
            if (securityAdvisorServiceEnterpriseDto.booleanAgree == 1)

               if (ToolUtil.isEmpty( getOne(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::enterpriseUserId, enterpriseId)
                               .eq(SecurityAdvisorServiceEnterprise::createBy, securityUtil!!.currUser.id)))) {

                   save(SecurityAdvisorServiceEnterprise().apply {
                       enterpriseUserId = enterpriseId

                   })
               }
            ResultUtil.success<Any>("处理成功")
        } ?: ResultUtil.error<Any>("当前信息不存在！")
    }

    override fun getCompanyTypeBySecurityAdvisorId(userId: String): String? {

        return getOne(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::createBy, userId)
                .orderByDesc(SecurityAdvisorServiceEnterprise::createTime)
                .eq(SecurityAdvisorServiceEnterprise::serviceStatus, true).last("limit 1")) ?.run {

            iEnterpriseUserService!!.getById(enterpriseUserId)?.companyType
        }
    }

    override fun getSecurityAdvisorServiceEnterprise(userId: String): SecurityAdvisorServiceEnterprise? {

        return getOne(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::createBy, userId)
                .orderByDesc(SecurityAdvisorServiceEnterprise::createTime)
                .eq(SecurityAdvisorServiceEnterprise::serviceStatus, true).last("limit 1"))
    }

    override fun getLeaveSecurity(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::serviceStatus, false)
                .orderByDesc(SecurityAdvisorServiceEnterprise::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { iSecurityAdvisorService!!.getOne(KtQueryWrapper(SecurityAdvisor::class.java)
                    .eq(SecurityAdvisor::userId, it!!.createBy))?.run { iSecurityAdvisorService.getSecurityAdvisorListVo(id) } }.toMutableList())

            ResultUtil.data(result, "获取离职的安全顾问成功！")
        } ?: ResultUtil.error(201, "暂无数据")
    }

    override fun getSecurityAdvisorLeaveEnterprise(userId: String): MutableList<EnterpriseUserListVo>? {

       return ToolUtil.setListToNul(list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java).eq(SecurityAdvisorServiceEnterprise::createBy,userId)
                .eq(SecurityAdvisorServiceEnterprise::serviceStatus, false)
                .orderByAsc(SecurityAdvisorServiceEnterprise::serviceBeginTime)))?.run {

            mapNotNull { iEnterpriseUserService!!.getEnterpriseUserVo(it?.enterpriseUserId!!) }.toMutableList()
        }
    }

}
